package com.qf.smartplatform.controller;

import com.qf.smartplatform.dto.Result;
import com.qf.smartplatform.events.UserLoginEvent;
import com.qf.smartplatform.pojo.User;
import com.qf.smartplatform.service.CategoryService;
import com.qf.smartplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * projectName:day12_27_Test
 * author:guoLei
 * time:2021/12/29 20:00
 * description:
 */
@RestController
@RequestMapping("/users")
public class UserController {

    private UserService userService;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @PostMapping("/user")
    public Result registry(@RequestBody User user) {
        userService.addUser(user);
        return Result.setOK();
    }


    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        User user = userService.login(username, password);
        session.setAttribute("user", user);
        context.publishEvent(new UserLoginEvent());
        return Result.setOK(user.getUsername());
    }

}
